package com.sz.biz.common.project.service.impl;

import com.sz.biz.common.AbstractBizService;
import com.sz.biz.common.constants.SystemConstants;
import com.sz.biz.common.customer.entity.CusCustomer;
import com.sz.biz.common.customer.service.CustomerService;
import com.sz.biz.common.platform.entity.PlatformCompany;
import com.sz.biz.common.platform.service.PlatformCompanyService;
import com.sz.biz.common.project.dto.*;
import com.sz.biz.common.project.entity.*;
import com.sz.biz.common.project.service.*;
import com.sz.biz.common.sup.dto.SupplierDto;
import com.sz.biz.common.sup.entity.Supplier;
import com.sz.biz.common.sup.service.SupplierService;
import com.sz.biz.logistics.constants.ProjectConstants;
import com.sz.biz.trade.constants.TrdErrorCodes;
import com.sz.common.base.constants.TemplateConstants;
import com.sz.common.base.dao.ParamData;
import com.sz.common.base.dto.QResultDto;
import com.sz.common.base.dto.QueryParams;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.utils.DateUtils;
import com.sz.common.base.utils.EntityUtils;
import com.sz.common.base.utils.JsonUtils;
import com.sz.common.base.utils.StringUtils;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.dto.OrgDto;
import com.sz.common.core.system.dto.OrgUserDto;
import com.sz.common.core.system.dto.UserDto;
import com.sz.common.core.system.entity.Org;
import com.sz.common.core.system.entity.SysFile;
import com.sz.common.core.system.entity.UserOrg;
import com.sz.common.core.system.service.OrgService;
import com.sz.common.core.system.service.SysFileService;
import com.sz.common.core.system.service.SysMailService;
import com.sz.common.core.system.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

/**
 * Function: ProjectServiceImpl. <br>
 * Date: 2017年07月13日 9:22 <br>
 * Author: wentao.chang
 */
@Service
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class ProjectServiceImpl extends AbstractBizService implements ProjectService {

    @Autowired
    private ProjectAuditService projectAuditService;
    @Autowired
    private ProjectFileService projectFileService;
    @Autowired
    private ProjectCompanyService projectCompanyService;
    @Autowired
    private ProjectQuestionService projectQuestionService;
    @Autowired
    private SysFileService sysFileService;

    @Autowired
    private SupplierService supplierService;
    @Autowired
    private CustomerService customerService;
    @Autowired
    private UserService userService;
    @Autowired
    private OrgService orgService;
    @Autowired
    private SysMailService sysMailService;

    @Autowired
    private PlatformCompanyService platformCompanyService;

    /**
     * 保存新项目
     *
     * @param project  project
     * @param issubmit issubmit
     */
    @Override
    public Integer save(ProjectDto project, boolean issubmit) {
        checkMain(project);
        checkCodeExist(project.getCode(), null, project.getBizTypeCode());
        Project prj = new Project();
        BeanUtils.copyProperties(project, prj);
        prj.setCreateUserId(PrincipalUtils.getAccountId());
        prj.setLastUpdateUserId(PrincipalUtils.getAccountId());
        prj.setIsReject(false);
        dao.save("ProjectMapper.insert", prj);
        //保存子表的信息
        //1.干系企业
        checkCompanyRepeat(project.getCompanys());
        project.getCompanys().forEach(projCompany -> {
            projCompany.setProjectId(prj.getId());
            projectCompanyService.save(projCompany);
        });
        //2.文件
        project.getFiles().forEach(projFile -> {
            projFile.setProjectId(prj.getId());
            projFile.setType(1);
            projectFileService.save(projFile);
        });
        if (issubmit) {
            updateProjectStatus(ProjectStatusEnum.WAITFIRSTTRIALSTATUS.getCode(), prj.getId());
            prj.setStatus(ProjectStatusEnum.WAITFIRSTTRIALSTATUS.getCode());
            sendEmail(prj);
            updateRejectStatus(prj.getId(), false);
            //删除历史审核
            projectAuditService.deleteByProjectId(prj.getId());
            //更新三个人为空
            dao.update("ProjectMapper.updateManNullById", prj.getId());
        }
        return prj.getId();
    }

    private void checkMain(ProjectDto project) {
        if (project.getOrgId() == null || project.getOrgId() == 0) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_ARGUMENT_ILLEGAL, "orgId");
        }
        if (StringUtils.isEmpty(project.getName())) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_ARGUMENT_ILLEGAL, "name");
        }
        if (StringUtils.isEmpty(project.getCode())) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_ARGUMENT_ILLEGAL, "code");
        }
    }

    /**
     * 修改新项目
     *
     * @param id       id
     * @param project  project
     * @param issubmit issubmit
     */
    @Override
    public void update(Integer id, ProjectDto project, boolean issubmit) {
        Project prj = findBaseById(id);
        //检查状态
        if (prj.getStatus() > ProjectStatusEnum.DRAFTSTATUS.getCode()) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_MODEL_HAS_SUBMITTED, id);
        }
        checkMain(project);
        checkCodeExist(project.getCode(), id, project.getBizTypeCode());
        prj.setRisk(project.getRisk());
        prj.setProfile(project.getProfile());
        prj.setValue(project.getValue());
        prj.setName(project.getName());
        prj.setCode(project.getCode());
        prj.setOrgId(project.getOrgId());
        prj.setLastUpdateUserId(PrincipalUtils.getAccountId());
        dao.update("ProjectMapper.update", prj);
        //保存子表的信息
        //1.干系企业
        checkCompanyRepeat(project.getCompanys());
        projectCompanyService.deleteByProjectId(id);
        project.getCompanys().forEach(projCompany -> {
            projCompany.setProjectId(prj.getId());
            projectCompanyService.save(projCompany);
        });
        //2.文件
        projectFileService.deleteByProjectId(id, 1);
        project.getFiles().forEach(projFile -> {
            projFile.setProjectId(prj.getId());
            projFile.setType(1);
            projectFileService.save(projFile);
        });
        if (issubmit) {
            updateProjectStatus(ProjectStatusEnum.WAITFIRSTTRIALSTATUS.getCode(), prj.getId());
            prj.setStatus(ProjectStatusEnum.WAITFIRSTTRIALSTATUS.getCode());
            sendEmail(prj);
            updateRejectStatus(prj.getId(), false);
            //删除历史审核
            projectAuditService.deleteByProjectId(id);
            //更新三个人为空
            dao.update("ProjectMapper.updateManNullById", id);
        }
    }


    private void checkCompanyRepeat(List<ProjectCompanyDto> companys) {
        if (CollectionUtils.isEmpty(companys)) {
            return;
        }
        Map<String, Object> map = new HashMap<>();
        for (ProjectCompanyDto company : companys) {
            if (map.containsKey(company.getType() + "-" + company.getCompanyId())) {
                throw Exceptions.bizException(TrdErrorCodes.ERROR_ARGUMENT_ILLEGAL, "company repeat");
            }
            map.put(company.getType() + "-" + company.getCompanyId(), company);
        }
    }

    private void checkCodeExist(String code, Integer id, String bizTypeCode) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("code", code);
        map.put("bizTypeCode", bizTypeCode);
        List<Project> projects = dao.findForList("ProjectMapper.findByCode", map, Project.class);
        if (!CollectionUtils.isEmpty(projects)) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_MODEL_CODE_EXIST, "");
        }
    }

    /**
     * 按ids提交审核
     *
     * @param ids ids
     */
    @Override
    public void submitByIds(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }

        ids.forEach(id -> {
            Project prj = findBaseById(id);
            if (prj.getStatus() != ProjectStatusEnum.DRAFTSTATUS.getCode()) {
                throw Exceptions.bizException(TrdErrorCodes.ERROR_MODEL_HAS_SUBMITTED);
            }
            List<ProjectCompany> listResult = projectCompanyService.queryByProjectId(id);
            Map<String, String> map = new HashMap<>();
            if (!CollectionUtils.isEmpty(listResult)) {
                listResult.forEach(company -> map.put(company.getType() + "-", "我是没用的字符串^.^"));
            }
            if (map.keySet().size() <= 1) {
                throw Exceptions.bizException(TrdErrorCodes.ERROR_PROJECT_MUST_HAVE_DIFFRENT_COMPANY, "");
            }
            updateProjectStatus(ProjectStatusEnum.WAITFIRSTTRIALSTATUS.getCode(), id);
            updateRejectStatus(id, false);
            //删除历史审核
            projectAuditService.deleteByProjectId(id);
            //更新三个人为空
            dao.update("ProjectMapper.updateManNullById", id);
            sendEmail(prj);
        });

    }

    private void sendEmail(Project project) {
        List<OrgUserDto> riskUserDtos = userService.findUserByOrgCode("SYS-GROUP-RISK"); //风控团队的人
        saveEmail(riskUserDtos, project, "风控");
        if (project.getStatus() < ProjectStatusEnum.WAITFINALTRIALSTATUS.getCode()) {
            List<OrgUserDto> finaceUserDtos = userService.findUserByOrgCode("SYS-GROUP-FD");//财务团队的人
            List<OrgUserDto> odUserDtos = userService.findUserByOrgCode("SYS-GROUP-OD");//运营团队的人
            saveEmail(finaceUserDtos, project, "财务");
            saveEmail(odUserDtos, project, "运营");
        }
    }

    public void saveEmail(List<OrgUserDto> userDtos, Project project, String orgCode) {
        if (userDtos.size() > 0) {
            userDtos.forEach(orgUserDto -> {
                        Map<String, Object> emailBodyMap = new HashMap<>();
                        emailBodyMap.put("projectname", project.getName());
                        emailBodyMap.put("submittime", DateUtils.formatDetailDate(dao.getDbDate()));
                        emailBodyMap.put("org", orgCode);
                        if (project.getBizTypeCode() == SystemConstants.BusinessType.LOGISTICS) {
                            emailBodyMap.put("bizType", "物流管理");
                        } else {
                            emailBodyMap.put("bizType", "贸易管理");
                        }
                        String emailBody = JsonUtils.toJSONString(emailBodyMap);
                        sysMailService.createMail(
                                "sys.logistics.master@hna.com", new String[]{orgUserDto.getEmail()},
                                "项目审批通知", emailBody,
                                project.getStatus() < ProjectStatusEnum.WAITFINALTRIALSTATUS.getCode() ? TemplateConstants.AUDIT_PROJECT_EMAIL : TemplateConstants.AUDIT_FINDL_PROJECT_EMAIL);
                    }
            );
        }
    }

    /**
     * 按id搜
     *
     * @param id id
     */
    @Override
    public Project findBaseById(Integer id) {
        return (Project) dao.findForObject("ProjectMapper.findBaseById", id);
    }

    /**
     * 按id搜
     *
     * @param id id
     */
    @Override
    public Project findDetailById(Integer id) {
        return (Project) dao.findForObject("ProjectMapper.findDetailById", id);
    }

    /**
     * 按ids搜
     *
     * @param ids ids
     */
    @Override
    public List<Project> findByIds(List<Integer> ids) {
        return dao.findForList("ProjectMapper.findByIds", ids, Project.class);
    }

    /**
     * 更新打回状态
     *
     * @param projectId projectId
     * @param isReject  isReject
     */
    @Override
    public void updateRejectStatus(Integer projectId, boolean isReject) {
        Map<String, Object> map = new HashMap<>();
        map.put("id", projectId);
        map.put("isReject", isReject);
        dao.update("ProjectMapper.updateRejectStatus", map);
    }

    /**
     * 按id搜详情
     *
     * @param id id
     */
    @Override
    public ProjectDto findDtoById(Integer id) {
        Project prj = findDetailById(id);
        ProjectDto dto = new ProjectDto();
        BeanUtils.copyProperties(prj, dto);
        //文件
        List<ProjectFile> files = projectFileService.queryByProjectId(id, 1);
        if (!CollectionUtils.isEmpty(files)) {
            List<String> fileIds = EntityUtils.getStringPropListFromBeans(files, "fileId");
            List<SysFile> fileInfos = sysFileService.getFileInfos(fileIds);
            Map<String, SysFile> fileMap = EntityUtils.getStringKeyMapFromBeans(fileInfos, "fileId");
            files.forEach(file -> {
                ProjectFileDto fileDto = new ProjectFileDto();
                BeanUtils.copyProperties(file, fileDto);
                SysFile sysfile = fileMap.get(file.getFileId());
                fileDto.setFileName(sysfile.getFileName());
                fileDto.setFilePath(sysfile.getFileLocation());
                fileDto.setContentType(sysfile.getContentType());
                dto.getFiles().add(fileDto);
            });
        }
        //干系企业
        List<ProjectCompany> companys = projectCompanyService.queryByProjectId(id);
        if (!CollectionUtils.isEmpty(companys)) {
            companys.forEach(company -> {
                ProjectCompanyDto companyDto = new ProjectCompanyDto();
                BeanUtils.copyProperties(company, companyDto);
                //供应商
                if (company.getType() == SystemConstants.CompanyType.SUPPLIER) {
                    SupplierDto sup = supplierService.findById(company.getCompanyId());
                    companyDto.setCompanyName(sup.getName());
                    companyDto.setCompanyCode(sup.getCode());
                }
                //客户
                if (company.getType() == SystemConstants.CompanyType.CUSTOMER) {
                    CusCustomer customer = customerService.findSimpleById(company.getCompanyId());
                    companyDto.setCompanyName(customer.getUserName());
                    companyDto.setCompanyCode(customer.getCode());
                }
                //平台
                if (company.getType() == SystemConstants.CompanyType.PLATFORM) {
                    PlatformCompany pcompany = platformCompanyService.getPlatformCompanyById(company.getCompanyId());
                    companyDto.setCompanyName(pcompany.getName());
                    companyDto.setCompanyCode(pcompany.getCode());
                }
                dto.getCompanys().add(companyDto);
            });
        }
        UserDto creater = userService.findUserDetailByUserId(prj.getCreateUserId());
        dto.setCreator(creater.getFullName() + " " + creater.getUserName());
        dto.setStatusName(getProjectStatusName(prj.getStatus()));
        //组织名称
        OrgDto org = orgService.findById(1, prj.getOrgId());
        dto.setOrgName(org.getShortName());
        return dto;
    }

    /**
     * 提交审核
     *
     * @param projectId    projectId
     * @param projectAudit projectAudit
     */
    @Override
    public void updateFirstAudit(Integer projectId, ProjectAudit projectAudit) {
        Project prj = findBaseById(projectId);
        if (prj.getStatus() != ProjectConstants.Status.PENDING_TRAL) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_MODEL_NOT_SUBMITTED, projectId);
        }
        //检查当前人是否在对应的用户组中
        Integer accountId = PrincipalUtils.getAccountId();
        List<UserOrg> uos = userService.getOrgByUserId(accountId);

        final boolean[] isInGroup = {false};
        final String[] man = {""};
        switch (projectAudit.getType()) {
            case 1: //风控
                Org orgRisk = orgService.findByOrgCode(2, "SYS-GROUP-RISK");
                if (prj.getRiskManId() != null && prj.getRiskManId() != 0) {
                    throw Exceptions.bizException(TrdErrorCodes.ERROR_PROJECT_HAS_THIS_FIRSTAUDIT);
                }
                uos.forEach(userOrg -> {
                    if (userOrg.getOrgId().equals(orgRisk.getId())) {
                        isInGroup[0] = true;
                        man[0] = "riskManId";
                    }
                });
                break;
            case 2: //财务
                Org orgFinance = orgService.findByOrgCode(2, "SYS-GROUP-FD");
                if (prj.getFinanceManId() != null && prj.getFinanceManId() != 0) {
                    throw Exceptions.bizException(TrdErrorCodes.ERROR_PROJECT_HAS_THIS_FIRSTAUDIT);
                }
                uos.forEach(userOrg -> {
                    if (userOrg.getOrgId().equals(orgFinance.getId())) {
                        isInGroup[0] = true;
                        man[0] = "financeManId";
                    }
                });
                break;
            case 3: //运营
                Org orgOd = orgService.findByOrgCode(2, "SYS-GROUP-OD");
                if (prj.getOperationManId() != null && prj.getOperationManId() != 0) {
                    throw Exceptions.bizException(TrdErrorCodes.ERROR_PROJECT_HAS_THIS_FIRSTAUDIT);
                }
                uos.forEach(userOrg -> {
                    if (userOrg.getOrgId().equals(orgOd.getId())) {
                        isInGroup[0] = true;
                        man[0] = "operationManId";
                    }
                });
                break;
            default:
                throw Exceptions.bizException(TrdErrorCodes.ERROR_ARGUMENT_ILLEGAL, "type");
        }
        if (!isInGroup[0]) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_PROJECT_NOT_IN_ORGGROUP);
        }

        projectAudit.setAuditorId(accountId);
        projectAudit.setProjectId(projectId);
        projectAuditService.save(projectAudit);
        // 如果有不通过 则直接变草稿
        if (projectAudit.getIsPass() != null && !projectAudit.getIsPass()) {
            updateProjectStatus(ProjectStatusEnum.DRAFTSTATUS.getCode(), projectId);
            updateRejectStatus(prj.getId(), true);
        } else {
            Map<String, Object> map = new HashMap<>();
            map.put("man", man[0]);
            map.put("manId", accountId);
            map.put("id", projectId);
            dao.update("ProjectMapper.updateFirstAuditMan", map);
        }
    }

    private void updateProjectStatus(int status, Integer projectId) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", status);
        map.put("id", projectId);
        dao.update("ProjectMapper.updateProjectStatus", map);
    }

    /**
     * 修改初审信息
     *
     * @param projectId     projectId
     * @param firstAuditMsg firstAuditMsg
     */
    @Override
    public void updateFirstAuditMsg(Integer projectId, String firstAuditMsg) {
        Project prj = findBaseById(projectId);
        if (prj.getFirstAuditTime() != null && prj.getStatus() != ProjectConstants.Status.PENDING_FINAL_APPEAL) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_MODEL_HAS_AUDITED);
        }
        //修改初审信息
        prj.setFirstAuditMsg(firstAuditMsg);
        prj.setFirstAuditTime(new Date());
        prj.setStatus(ProjectStatusEnum.WAITFINALTRIALSTATUS.getCode());
        dao.update("ProjectMapper.updateFirstAuditMsg", prj);
        sendEmail(prj);
    }

    /**
     * 修改终审信息
     *
     * @param projectId     projectId
     * @param finalAuditMsg finalAuditMsg
     * @param isPass        isPass
     */
    @Override
    public void updateFinalAuditMsg(Integer projectId, String finalAuditMsg, boolean isPass) {
        Project prj = findBaseById(projectId);
        if (prj.getFinalManId() != null && prj.getFinalManId() != 0) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_MODEL_HAS_AUDITED);
        }
        if (StringUtils.isEmpty(finalAuditMsg)) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_ARGUMENT_ILLEGAL, "finalAuditMsg");
        }
        //修改终审信息
        prj.setFinalAuditMsg(finalAuditMsg);
        prj.setFinalAuditTime(new Date());
        prj.setFinalManId(PrincipalUtils.getAccountId());
        prj.setStatus(isPass ? ProjectStatusEnum.APPROVEDSTATUS.getCode() : ProjectStatusEnum.CLOSEDPSTATUS.getCode());
        dao.update("ProjectMapper.updateFinalAuditMsg", prj);
    }

    /**
     * 正常结项
     *
     * @param projectId  projectId
     * @param projectDto projectDto
     */
    @Override
    public void closeProject(Integer projectId, ProjectDto projectDto) {
        Project prj = findBaseById(projectId);
        if (prj.getStatus() != ProjectStatusEnum.APPROVEDSTATUS.getCode()) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_PROJECT_HAS_NOT_FINALAUDIT);
        }
        //合同
        List<ProjectFile> projectFiles = projectFileService.queryByProjectId(projectId, 3);
        if (projectFiles == null || projectFiles.size() <= 0) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_PROJECT_HAS_NOT_CONTRACT_FILE);
        }
        List<ProjectFileDto> list = projectDto.getFiles();
        if (!CollectionUtils.isEmpty(list)) {
            list.forEach(item -> {
                item.setProjectId(projectId);
                projectFileService.save(item);
            });
        }
        prj.setStatus(5);
        prj.setSummary(projectDto.getSummary());
        dao.update("ProjectMapper.closeProject", prj);
    }

    /**
     * 按ids删除项目
     *
     * @param ids ids
     */
    @Override
    public void deleteByIds(List<Integer> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return;
        }
        ids.forEach(prjId -> {
            Project prj = findBaseById(prjId);
            if (prj.getStatus() > ProjectStatusEnum.DRAFTSTATUS.getCode()) {
                throw Exceptions.bizException(TrdErrorCodes.ERROR_MODEL_NOT_SAVED);
            }
            dao.update("ProjectMapper.deleteById", prjId);
        });
    }

    /**
     * 查询项目列表
     *
     * @param qp qp
     */
    @Override
    public QResultDto findByFilter(QueryParams qp) {
        ParamData pd = this.convertQueryParams(qp);
        pd.putAll(userProjectPermission());
        List<Project> projects = dao.findForList("ProjectMapper.findByFilterListPage", pd, Project.class);
        List<ProjectDto> pDtos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(projects)) {
            projects.forEach(prj -> {
                ProjectDto dto = new ProjectDto();
                BeanUtils.copyProperties(prj, dto);
                UserDto creater = userService.findUserDetailByUserId(prj.getCreateUserId());
                dto.setCreator(creater.getFullName() + " " + creater.getUserName());
                List<ProjectCompany> companys = projectCompanyService.queryByProjectId(prj.getId());
                StringBuilder companyNames = new StringBuilder();
                if (!CollectionUtils.isEmpty(companys)) {
                    companys.forEach(company -> {
                        ProjectCompanyDto companyDto = new ProjectCompanyDto();
                        BeanUtils.copyProperties(company, companyDto);
                        //供应商
                        if (company.getType() == SystemConstants.CompanyType.SUPPLIER) {
                            Supplier sup = supplierService.findSimpleById(company.getCompanyId());
                            companyDto.setCompanyName(sup.getName());
                            companyDto.setCompanyCode(sup.getCode());
                            dto.getCompanys().add(companyDto);
                        }
                        //客户
                        if (company.getType() == SystemConstants.CompanyType.CUSTOMER) {
                            CusCustomer customer = customerService.findSimpleById(company.getCompanyId());
                            companyDto.setCompanyName(customer.getUserName());
                            companyDto.setCompanyCode(customer.getCode());
                            dto.getCompanys().add(companyDto);
                        }
                        //平台
                        if (company.getType() == SystemConstants.CompanyType.PLATFORM) {
                            PlatformCompany pcompany = platformCompanyService.getPlatformCompanyById(company.getCompanyId());
                            companyDto.setCompanyName(pcompany.getName());
                            companyDto.setCompanyCode(pcompany.getCode());
                            dto.getCompanys().add(companyDto);
                        }
                        companyNames.append(companyDto.getCompanyName()).append("，");
                    });
                }
                dto.setCompanyNames(companyNames.length() > 0 ? companyNames.substring(0, companyNames.length() - 1) : "");
                dto.setStatusName(getProjectStatusName(prj.getStatus()));
                pDtos.add(dto);
            });
        }
        return new QResultDto(pDtos, pd.getPagination());
    }

    /**
     * 查询项目列表短接口
     *
     * @param params params
     */
    @Override
    public QResultDto findShortByFilter(QueryParams params) {
        ParamData pd = this.convertQueryParams(params);
        pd.putAll(userProjectPermission());
        List<Project> projects = dao.findForList("ProjectMapper.findShortByFilterListPage", pd, Project.class);
        return new QResultDto(projects, pd.getPagination());
    }

    /**
     * 贸易相关的组权限
     *
     * @return Map
     */
    @Override
    public Map<String, Object> userProjectPermission() {
        Map<String, Object> map = new HashMap<>();
        Integer accountId = PrincipalUtils.getAccountId();
        List<UserOrg> uos = userService.getOrgByUserId(accountId);
        List<Integer> userGroupIds = new ArrayList<>();
        //运营、财务、风控组可以查看所有订单
        boolean isInApprovalGroup = false;
        boolean isInSysGroup = false;
        if (null != uos && uos.size() > 0) {
            Org orgRisk = orgService.findByOrgCode(2, "SYS-GROUP-RISK");
            Org orgOd = orgService.findByOrgCode(2, "SYS-GROUP-OD");
            Org orgFinance = orgService.findByOrgCode(2, "SYS-GROUP-FD");
            Org orgSys = orgService.findByOrgCode(2, "SYS-GROUP-SYS");
            for (UserOrg userOrg : uos) {
                userGroupIds.add(userOrg.getOrgId());
                if (null != orgRisk) {
                    if (userOrg.getOrgId().equals(orgRisk.getId())) {
                        isInApprovalGroup = true;
                    }
                }
                if (null != orgOd) {
                    if (userOrg.getOrgId().equals(orgOd.getId())) {
                        isInApprovalGroup = true;
                    }
                }
                if (null != orgFinance) {
                    if (userOrg.getOrgId().equals(orgFinance.getId())) {
                        isInApprovalGroup = true;
                    }
                }
                if (null != orgSys) {
                    if (userOrg.getOrgId().equals(orgSys.getId())) {
                        isInSysGroup = true;
                    }
                }
            }
        }
        if (userGroupIds.size() <= 0) {
            userGroupIds.add(-1);
        }
        map.put("isInApprovalGroup", isInApprovalGroup);
        map.put("isInSysGroup", isInSysGroup || accountId == 1);
        map.put("userGroupIds", userGroupIds);
        map.put("createrId", accountId);
        return map;
    }


    /**
     * 查询项目列表,没有分页
     *
     * @param orderType   orderType
     * @param sellerId    sellerId
     * @param purchaserId purchaserId
     * @return List
     */
    @Override
    public List<Project> findSimpleProjects(String orderType, Integer sellerId, Integer purchaserId) {
        ParamData pd = new ParamData();
        pd.put("biztype", "2");
        pd.put("orderType", orderType);
        pd.put("sellerId", sellerId);
        pd.put("purchaserId", purchaserId);
        return dao.findForList("ProjectMapper.findSimpleProjects", pd, Project.class);
    }

    @Override
    public List<ProjectUserOrgDto> getProjectUserOrg(int userId) {
        List<UserOrg> userOrgs = userService.getOrgByUserId(userId);
        Org orgFinance = orgService.findByOrgCode(2, "SYS-GROUP-FD");
        Org orgOd = orgService.findByOrgCode(2, "SYS-GROUP-OD");
        Org orgRisk = orgService.findByOrgCode(2, "SYS-GROUP-RISK");
        List<ProjectUserOrgDto> results = new ArrayList<>();
        if (userOrgs != null) {
            userOrgs.forEach(userOrg -> {
                ProjectUserOrgDto projectUserOrgDto = new ProjectUserOrgDto();
                BeanUtils.copyProperties(userOrg, projectUserOrgDto);
                if (orgFinance.getId().equals(projectUserOrgDto.getOrgId())) {
                    projectUserOrgDto.setType(2);
                }
                if (orgOd.getId().equals(projectUserOrgDto.getOrgId())) {
                    projectUserOrgDto.setType(3);
                }
                if (orgRisk.getId().equals(projectUserOrgDto.getOrgId())) {
                    projectUserOrgDto.setType(1);
                }
                if (projectUserOrgDto.getType() != 0) {
                    results.add(projectUserOrgDto);
                }
            });
        }
        return results;
    }

    @Override
    public ProjectProcessStatusDto getProjectProcessStatus(int projectId) {
        ProjectProcessStatusDto dto = new ProjectProcessStatusDto();
        Project prj = findDetailById(projectId);
        BeanUtils.copyProperties(prj, dto);
        UserDto creater = userService.findUserDetailByUserId(prj.getCreateUserId());
        dto.setCreator(creater.getFullName());
        dto.setStatusName(getProjectStatusName(prj.getStatus()));
        if (!StringUtils.isEmpty(prj.getFinalManId()) && prj.getFinalManId() != 0) {
            UserDto finalUser = userService.findUserDetailByUserId(prj.getFinalManId());
            if (finalUser != null) {
                dto.setFinalManName(finalUser.getFullName());
            }
        }
        OrgDto org = orgService.findById(1, prj.getOrgId());
        dto.setOrgName(org.getName());
        ProjectAuditInfoDto riskAudit = projectAuditService.getProjectAuditInfoDtoByProjectIdAndType(projectId, 1);
        ProjectAuditInfoDto financeAudit = projectAuditService.getProjectAuditInfoDtoByProjectIdAndType(projectId, 2);
        ProjectAuditInfoDto odAudit = projectAuditService.getProjectAuditInfoDtoByProjectIdAndType(projectId, 3);
        if (riskAudit != null) {
            riskAudit.setType(1);
            dto.getProjectAuditInfoDtos().add(riskAudit);
        } else {
            ProjectAuditInfoDto riskAuditEmpty = new ProjectAuditInfoDto();
            riskAuditEmpty.setType(1);
            dto.getProjectAuditInfoDtos().add(riskAuditEmpty);
        }
        if (financeAudit != null) {
            financeAudit.setType(2);
            dto.getProjectAuditInfoDtos().add(financeAudit);
        } else {
            ProjectAuditInfoDto financeAuditEmpty = new ProjectAuditInfoDto();
            financeAuditEmpty.setType(2);
            dto.getProjectAuditInfoDtos().add(financeAuditEmpty);
        }
        if (odAudit != null) {
            odAudit.setType(3);
            dto.getProjectAuditInfoDtos().add(odAudit);
        } else {
            ProjectAuditInfoDto odAuditEmpty = new ProjectAuditInfoDto();
            odAuditEmpty.setType(3);
            dto.getProjectAuditInfoDtos().add(odAuditEmpty);
        }
        return dto;
    }

    @Override
    public void addAskQuestion(ProjectQuestion projectQuestion, int projectId) {
        Project prj = findBaseById(projectId);
        if (prj.getStatus() != ProjectConstants.Status.PENDING_TRAL) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_MODEL_NOT_SUBMITTED, projectId);
        }
        //检查当前人是否在对应的用户组中
        Integer accountId = PrincipalUtils.getAccountId();
        List<UserOrg> uos = userService.getOrgByUserId(accountId);
        final boolean[] isInGroup = {false};
        Org orgRisk = orgService.findByOrgCode(2, "SYS-GROUP-RISK");
        uos.forEach(userOrg -> {
            if (userOrg.getOrgId().equals(orgRisk.getId())) {
                isInGroup[0] = true;
            }
        });
        Org orgFinance = orgService.findByOrgCode(2, "SYS-GROUP-FD");
        uos.forEach(userOrg -> {
            if (userOrg.getOrgId().equals(orgFinance.getId())) {
                isInGroup[0] = true;
            }
        });
        Org orgOd = orgService.findByOrgCode(2, "SYS-GROUP-OD");
        uos.forEach(userOrg -> {
            if (userOrg.getOrgId().equals(orgOd.getId())) {
                isInGroup[0] = true;
            }
        });
        if (!isInGroup[0] && (projectQuestion.getQuestionId() == null || projectQuestion.getQuestionId() == 0)) {
            throw Exceptions.bizException(TrdErrorCodes.ERROR_PROJECT_NOT_IN_ORGGROUP);
        }
        projectQuestionService.addQuestion(projectQuestion);
    }

    /**
     * 校验项目编码
     *
     * @param id          id
     * @param code        code
     * @param bizTypeCode bizTypeCode
     */
    @Override
    public void codeCheck(int id, String code, String bizTypeCode) {
        checkCodeExist(code, id, bizTypeCode);
    }
}
